package com.gcph.zhuoba.player.activitys;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.bean.Resource;
import com.gcph.zhuoba.main.bean.ResourceData;
import com.gcph.zhuoba.main.common.BaseActivity;
import com.gcph.zhuoba.main.common.CommonVedioActivity;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.player.client.PlayerImitateClient;
import com.gcph.zhuoba.util.DownImage;
import com.gcph.zhuoba.util.L;
import com.google.gson.Gson;

/**
 * 会员模仿的activity
 * @author Administrator
 */
public class PlayerImitateActivity extends BaseActivity {
	//退出
    private Button btn_practice_quit;
    private Button btn_practice_full_screnn;
    private Button btn_re_imitate;
    
    //线路开关
    private ToggleButton btn_imitate_line;
    //球型数据
    private ImageView resource_img;
    private Resource resource;
    private static Handler socketHandler;
    private PlayerImitateClient socketClient;
    
    @SuppressLint("SimpleDateFormat")
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.fullScreen(true);
		setContentView(R.layout.activity_player_imitate);
		Intent intent = this.getIntent(); 
		//得到当前教案的详细信息
		resource=(Resource)intent.getSerializableExtra("resource");
		viewInitAndSetClickListener();
		
		L.d("resource.getVideoFileUrl==="+resource.getVideoFileUrl());
		L.d("resource.getResourceData==="+resource.getResourceData());
		
		socketClient = PlayerImitateClient.getInstance();
		
		socketHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            	//配对失败
            	if(PlayerImitateClient.PAIR_FAIL == msg.what)
            	{
            		Toast.makeText(PlayerImitateActivity.this, "与终端配对失败", Toast.LENGTH_SHORT).show();
            		finish();
            	}
            	//配对成功
            	if(PlayerImitateClient.PAIR_SUCC == msg.what)
            	{
            		//调用我要模仿接口
            		doImitate(Constant.SOCKET_METHOD_PLAYER_IMITATE);
        			//不等socket反馈信息，直接提示
        			Toast.makeText(PlayerImitateActivity.this, "请按桌面提示进行操作", Toast.LENGTH_LONG).show();
            	}
            }
		};
		
		
		//----------------------配对开始----------------------------
		new Thread(new Runnable() {
			@Override
			public void run() {
				String socket_ip = getResources().getString(R.string.socket_ip);
				int socket_port = Integer.parseInt(getResources().getString(R.string.socket_port));
				socketClient.setUpConnection(socket_ip,socket_port,socketHandler);
				L.d("======请求配对=====");
				socketClient.send("{\"method\":\"102\",\"deviceid\":\"1\",\"username\":\"test\"}");
				socketClient.handleReceive(socketHandler);
			}
		}).start();
		//----------------------配对结束----------------------------
		
	}
	
	private void doImitate(final Integer method)
	{
		new Runnable() {
			@Override
			public void run() {
				if(null != resource && null !=resource.getResourceData())
				{
					ResourceData rd = new Gson().fromJson(resource.getResourceData(), ResourceData.class);
					final String fileTime = sdf.format(new Date());
	            	final String imitateNo = "imitate_"+fileTime;
	                int power=0;
	                double jiasaiX=0;
	                double jiasaiY=0;
	                try{
	                	power = rd.getBallPower();
	                	jiasaiX = rd.getJiasaiX()/2.0+0.5;
	                	jiasaiY = rd.getJiasaiY()/2.0+0.5;
	                }catch(Exception e)
	                {
	                	e.printStackTrace();
	                }
	                
					StringBuilder sb = new StringBuilder();
					sb.append("{\"method\":\"");
					sb.append(method);
					sb.append("\",\"no\":\"");
					sb.append(imitateNo);
					sb.append("\",\"data\":\"");
					sb.append(rd.getBallsPositionData());
					sb.append("\",\"line\":\"");
					sb.append(resource.getResourceLine());
					sb.append("\",\"jiasaiX\":\"");
					sb.append(jiasaiX);
					sb.append("\",\"jiasaiY\":\"");
					sb.append(jiasaiY);
					sb.append("\",\"power\":\"");
					sb.append(power);
					sb.append("\"}");
					
					socketClient.send(sb.toString());
				}
			}
		}.run();
	}
	
	/**
	 * 
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == 0){
			if(null != socketClient)
			{
				socketClient.exit();
			}
			finish();
        } 
		
		if(resultCode == 1){
			
        }
    }
	
	private void viewInitAndSetClickListener()
	{
		
		btn_practice_full_screnn = (Button) this.findViewById(R.id.btn_practice_full_screnn);
	    btn_practice_quit = (Button) this.findViewById(R.id.btn_practice_quit);
	    btn_re_imitate = (Button) this.findViewById(R.id.btn_re_imitate);
	    btn_imitate_line = (ToggleButton) this.findViewById(R.id.btn_imitate_line);
	    resource_img = (ImageView) this.findViewById(R.id.resource_img);
	    //加载球型数据图片
		DownImage downImage = new DownImage(resource_img);
		downImage.execute(getResources().getString(R.string.server_root_url) + resource.getImgFileUrl());
	    btn_practice_quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	//退出断开连接
            	socketClient.exit();
            	finish();
            }
        });
	    
	    //录像全屏
	    btn_practice_full_screnn.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		Intent intent = new Intent(PlayerImitateActivity.this,CommonVedioActivity.class);
				intent.putExtra("videoFileUrl", resource.getVideoFileUrl());
				startActivity(intent);
	    	}
	    });
	    
	    //重新模仿
	    btn_re_imitate.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		doImitate(Constant.SOCKET_METHOD_PLAYER_REMITATE);
	    	}
	    });
	    
	    //线路开关
	    btn_imitate_line.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		final boolean checkedFlag = btn_imitate_line.isChecked();
	    		new Runnable() {
					@Override
					public void run() {
						if(checkedFlag)
			    		{
							socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_IMITATE_SWITCH + "\",\"data\":\"on\"}");
			    		}else
			    		{
			    			socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_IMITATE_SWITCH + "\",\"data\":\"off\"}");
			    		}
					}
				}.run();
	    		
	    	}
	    });
	    
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
}